package com.sghd.football.module.game.service.config;

import com.sghd.football.module.data.dao.MysqlTemplate;
import com.sghd.football.module.data.entity.GameLine;
import com.sghd.football.module.game.service.config.model.ConfigRoom;
import com.sghd.football.module.game.service.core.ChessType;
import com.sghd.football.module.game.service.core.Rule;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * \* Created with 王创辉.
 * \* Date: 2018/5/21
 * \* Time: 12:15
 * \* @desc:
 */
public abstract class AbstractTemplete implements ConfigService {

    /** 重载配置锁*/
    public static ReadWriteLock lock = new ReentrantReadWriteLock(true);

    /** 所有房间配置缓存*/
    protected ConcurrentMap<Integer, ConfigRoom> configRooms = new ConcurrentHashMap<>();
    @Autowired
    protected MysqlTemplate querier;
    /** 由不同数据来源实现*/
    public abstract void read();
    public abstract void reload();

    @PostConstruct
    public void init(){
       lock.writeLock().lock();
        try {
            read();
            ChessType.init(this.configRooms.values());
            DetachedCriteria criteria = DetachedCriteria.forClass(GameLine.class);
            criteria.addOrder(Order.asc("id"));
            List<GameLine> gameLines = querier.find(criteria);
            Rule.init(gameLines);//初始化规则
        } finally {
            lock.writeLock().unlock();
        }
    }
    @Override
    public ConfigRoom getConfig(int roomId) {
        return configRooms.get(roomId);
    }
}
